package com.ruicar.afs.cloud.channel.grade.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.channel.grade.dto.GradeModelElementListDTO;
import com.ruicar.afs.cloud.channel.grade.entity.GradeModelElement;
import com.ruicar.afs.cloud.channel.grade.entity.GradeModelElementList;
import com.ruicar.afs.cloud.channel.grade.service.GradeModelElementListService;
import com.ruicar.afs.cloud.channel.grade.service.GradeModelElementService;
import com.ruicar.afs.cloud.channel.grade.vo.GradeModelElementVO;
import com.ruicar.afs.cloud.channel.grade.vo.TreeNode;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/grade/gradeModelElementList")
@Api(value = "grade", description = " 评级指标评要素模块controller")
public class GradeModelElementListController {
    private static final Logger logger = LoggerFactory.getLogger(GradeModelElementListController.class);

    @Autowired
    private GradeModelElementService gradeModelElementService;
    @Autowired
    private GradeModelElementListService gradeModelElementListService;

    @RequestMapping(value = "/getVoByModelCodeAndElementNo", method = RequestMethod.POST)
    @ApiOperation(value = "根据ModelCode和ElementNo查询评级模型评分项信息，进入评分项目配置页面用")
    public IResponse<List<GradeModelElementVO>> getVoByModelCodeAndElementNo(@RequestBody GradeModelElement gradeModelElement) {
        if (gradeModelElement == null) {
            return IResponse.fail("必传参数不能为空，请联系管理员！");
        }
        logger.info("getVoByModelCodeAndElementNo方法输入参数：---->" + JSONObject.toJSONString(gradeModelElement));
        if (StringUtils.isBlank(gradeModelElement.getModelCode()) || StringUtils.isBlank(gradeModelElement.getElementNo())) {
            return IResponse.fail("必传参数不能为空，请联系管理员！");
        }
        List<GradeModelElementVO> returnVoList = new ArrayList<GradeModelElementVO>();
        try {
            List<GradeModelElement> gradeModelElementList = gradeModelElementService.list(Wrappers.<GradeModelElement>query().lambda()
                    .eq(GradeModelElement::getModelCode, gradeModelElement.getModelCode())
                    .eq(GradeModelElement::getElementNo, gradeModelElement.getElementNo()));
            if (CollectionUtils.isNotEmpty(gradeModelElementList)) {
                GradeModelElement element = gradeModelElementList.get(0);

                List<GradeModelElementList> gradeModelElementListList = gradeModelElementListService.list(Wrappers.<GradeModelElementList>query().lambda()
                        .eq(StringUtils.isNotBlank(gradeModelElement.getModelCode()), GradeModelElementList::getModelCode, gradeModelElement.getModelCode())
                        .eq(StringUtils.isNotBlank(gradeModelElement.getElementNo()), GradeModelElementList::getElementNo, gradeModelElement.getElementNo())
                        .orderByAsc(GradeModelElementList::getSeqno)
                        .orderByAsc(GradeModelElementList::getId));
                if (CollectionUtils.isNotEmpty(gradeModelElementListList)) {
                    for (GradeModelElementList elementList : gradeModelElementListList) {
                        GradeModelElementVO vo = new GradeModelElementVO();
                        BeanUtils.copyProperties(element, vo);
                        BeanUtils.copyProperties(elementList, vo);
                        vo.setElementNo(elementList.getElementNo());
                        vo.setModelCode(elementList.getModelCode());
                        vo.setHighLimit(elementList.getHighLimit());
                        vo.setLowLimit(elementList.getLowLimit());
                        vo.setHighLimitBack(elementList.getHighLimit());
                        vo.setLowLimitBack(elementList.getLowLimit());
                        if (vo.getElementEditType().equals("0")) {
                            vo.setElementDataDic(vo.getElementEditSrc() + "." + vo.getElementValue());
                        }
                        returnVoList.add(vo);
                    }
                }
            }
            return IResponse.success("查询成功").setData(returnVoList);
        } catch (BeansException e) {
            logger.error(e.getMessage(), e);
            return IResponse.fail("查询失败，请联系管理员！");
        }
    }

    @RequestMapping(value = "/getGradeModelElementTreeNode", method = RequestMethod.POST)
    @ApiOperation(value = "获取评级指标树节点")
    public IResponse<List<TreeNode>> getGradeModelElementTreeNode(@RequestParam String modelCode) {
        logger.info("getGradeModelElementTreeNode方法输入参数：---->" + modelCode);
        List<GradeModelElementVO> returnVoList = new ArrayList<GradeModelElementVO>();
        List<TreeNode> list = new ArrayList<TreeNode>();
        try {
            List<GradeModelElement> gradeModelElementList = gradeModelElementService.list(Wrappers.<GradeModelElement>query().lambda()
                    .eq(org.apache.commons.lang.StringUtils.isNotBlank(modelCode), GradeModelElement::getModelCode, modelCode)
                    .orderByAsc(GradeModelElement::getElementNo)
                    .orderByAsc(GradeModelElement::getSeqno));

            if (CollectionUtils.isNotEmpty(gradeModelElementList)) {
                GradeModelElement element = gradeModelElementList.get(0);
                if (CollectionUtils.isNotEmpty(gradeModelElementList)) {
                    for (GradeModelElement gradeModelElement : gradeModelElementList) {
                        list.add(this.convert(gradeModelElement));
                    }
                }
            }
            return IResponse.success("查询成功").setData(list);
        } catch (BeansException e) {
            logger.error(e.getMessage(), e);
            return IResponse.fail("查询失败，请联系管理员！");
        }
    }

    /**
     * @Description: 转换树节点
     * @param: [gradeModelElement]
     * @return: TreeNode
     * @auther: jiangxiongfei
     * @date: 2020-08-11 20:44
     */
    private TreeNode convert(GradeModelElement gradeModelElement) {
        TreeNode node = new TreeNode();
        node.setCanSelected(true);
        node.setId(org.apache.commons.lang.StringUtils.strip(gradeModelElement.getElementNo()).replaceAll("\\u0000", ""));
        node.setPid(org.apache.commons.lang.StringUtils.strip(gradeModelElement.getUpElementNo()).replaceAll("\\u0000", ""));
        node.setText(gradeModelElement.getElementName());
        node.setHasChild(false);
        return node;
    }

    @Transactional
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "键盘页面，配置指标修改后保存")
    public IResponse<GradeModelElementList> update(@RequestBody GradeModelElementListDTO dto) {
        if (dto == null) {
            return IResponse.fail("输入参数为空，请联系管理员！");
        }
        logger.info("update 方法(键盘页面，配置指标修改后保存)输入参数：---->" + JSONObject.toJSONString(dto));
        try {
            //注意，批量方法默认的是1000条，集合不能超过1000条
            if (CollectionUtils.isNotEmpty(dto.getDelete())) {
                List<Long> idList = new ArrayList<Long>();
                for (GradeModelElementList gradeModelElementList : dto.getDelete()) {
                    idList.add(gradeModelElementList.getId());
                }
                gradeModelElementListService.removeByIds(idList);
            }

            if (CollectionUtils.isNotEmpty(dto.getUpdate())) {
                //获取指标种类（数据字典，区间定值，其它）
                GradeModelElement element = gradeModelElementService.getOne(Wrappers.<GradeModelElement>query().lambda()
                        .eq(GradeModelElement::getModelCode, dto.getUpdate().get(0).getModelCode())
                        .eq(GradeModelElement::getElementNo, dto.getUpdate().get(0).getElementNo()));

                List<GradeModelElementList> gradeModelElementLists = gradeModelElementListService.list(Wrappers.<GradeModelElementList>query().lambda()
                        .eq(GradeModelElementList::getModelCode, dto.getUpdate().get(0).getModelCode())
                        .eq(GradeModelElementList::getElementNo, dto.getUpdate().get(0).getElementNo()));
                if (CollectionUtils.isNotEmpty(gradeModelElementLists)) {
                    for (GradeModelElementList gradeModelElementList : gradeModelElementLists) {
                        for (GradeModelElementList gradeModelElementList1 : dto.getUpdate()) {
                            if ("0".equals(element.getElementEditType())) { //0-数据字典
                                if (gradeModelElementList.getElementValue().equals(gradeModelElementList1.getElementValue())) {
                                    //手动开启事务回滚
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return IResponse.fail("同一个要素值不能重复配置多次！");
                                } else if ("1".equals(element.getElementEditType())) { //1-区间定值
                                    //todo 区间是否包含判断，或者前台判断

                                } else { //2-其它

                                }
                            }
                        }
                    }
                }
                gradeModelElementListService.updateBatchById(dto.getUpdate());
            }
            if (CollectionUtils.isNotEmpty(dto.getInsert())) {
                //获取指标种类（数据字典，区间定值，其它）
                GradeModelElement element = gradeModelElementService.getOne(Wrappers.<GradeModelElement>query().lambda()
                        .eq(GradeModelElement::getModelCode, dto.getInsert().get(0).getModelCode())
                        .eq(GradeModelElement::getElementNo, dto.getInsert().get(0).getElementNo()));

                List<GradeModelElementList> gradeModelElementLists = gradeModelElementListService.list(Wrappers.<GradeModelElementList>query().lambda()
                        .eq(GradeModelElementList::getModelCode, dto.getInsert().get(0).getModelCode())
                        .eq(GradeModelElementList::getElementNo, dto.getInsert().get(0).getElementNo()));
                if (CollectionUtils.isNotEmpty(gradeModelElementLists)) {
                    for (GradeModelElementList gradeModelElementList : gradeModelElementLists) {
                        for (GradeModelElementList gradeModelElementList1 : dto.getInsert()) {
                            if ("0".equals(element.getElementEditType())) { //0-数据字典
                                if (gradeModelElementList.getElementValue().equals(gradeModelElementList1.getElementValue())) {
                                    //手动开启事务回滚
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return IResponse.fail("同一个要素值不能重复配置多次！");
                                } else if ("1".equals(element.getElementEditType())) { //1-区间定值
                                    //todo 区间是否包含判断，或者前台判断

                                } else { //2-其它

                                }
                            }
                        }
                    }
                }
                gradeModelElementListService.saveBatch(dto.getInsert());
            }
            return IResponse.success("保存成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //手动开启事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return IResponse.fail("保存失败，请联系管理员！");
        }
    }
}
